// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package service_cmd

import (
	"fmt"
	"io"
	"os"
	"os/exec"
	"os/user"

	"gitcode.com/opendragonfly/df_server/utils"
	"github.com/spf13/cobra"
)

const _SYSTEMD_CONTENT = `
[Unit]
Description=OpenDragonFly trace track server
After=network.target

[Service]
User=dragonfly
ExecStart=/usr/sbin/dragonfly service run
ExecStop=/usr/bin/kill -9 $MAINPID
Restart=on-failure


[Install]
WantedBy=multi-user.target
`

var installCmd = &cobra.Command{
	Use: "install",
	RunE: func(cmd *cobra.Command, args []string) error {
		//检查是否是root用户
		curUser, err := user.Current()
		if err != nil {
			return err
		}
		if curUser.Uid != "0" {
			return fmt.Errorf("need root to run this command")
		}
		//检查是否要初始化配置文件
		_, err = os.Stat(utils.CONFIG_FILE_PATH)
		if err != nil {
			cfgInitCmd := exec.Command(os.Args[0], "config", "install")
			err = cfgInitCmd.Run()
			if err != nil {
				return err
			}
		}
		//安装目标文件
		srcFile, err := os.Open(os.Args[0])
		if err != nil {
			return err
		}
		defer srcFile.Close()
		destFile, err := os.Create(utils.EXEC_FILE_PATH)
		if err != nil {
			return err
		}
		defer destFile.Close()
		_, err = io.Copy(destFile, srcFile)
		if err != nil {
			return err
		}
		//设置执行权限
		err = os.Chmod(utils.EXEC_FILE_PATH, 0555)
		if err != nil {
			return err
		}
		//设置用户
		uid, gid, err := utils.GetUidAndGid()
		if err != nil {
			return err
		}
		err = os.Chown(utils.EXEC_FILE_PATH, uid, gid)
		if err != nil {
			return err
		}
		//创建数据目录
		os.MkdirAll(utils.DATA_DIR_PATH, 0700) //skip error check
		err = os.Chown(utils.DATA_DIR_PATH, uid, gid)
		if err != nil {
			return err
		}
		//写入systemd service文件
		err = os.WriteFile(utils.SERVICE_FILE_PATH, []byte(_SYSTEMD_CONTENT), 0644)
		if err != nil {
			return err
		}
		//重载systemd
		reloadCmd := exec.Command("/usr/bin/systemctl", "daemon-reload")
		err = reloadCmd.Run()
		if err != nil {
			return err
		}
		//设置开机启动
		enableCmd := exec.Command("/usr/bin/systemctl", "enable", "dragonfly")
		err = enableCmd.Run()
		if err != nil {
			return err
		}

		fmt.Println("install success")
		return nil
	},
}
